<template>

  <h1>{{chapterDate.chaName}}</h1>
  <div class="ql-container ql-snow">
    <mavon-editor  v-model="content" default-open="preview"
                   :toolbarsFlag="false"
                   :subfield="false" style="height:calc(100vh - 260px)"/>
  </div>


  <el-divider content-position="left"><h1>代码在线测试</h1></el-divider>
  <el-button type="primary" @click="codeTest" style="margin-top: 10px">点击此处进行代码测试</el-button>
<!--  <el-button type="success" round>{{study}}</el-button>-->
  <el-divider content-position="left">视频学习</el-divider>
  <div class="video">
    <el-tag
        :type="this.study === 3 ? 'primary' : 'success'"
        disable-transitions>{{this.study === 3 ? '完成' : '未完成'}}
    </el-tag>
    <div id="J_prismPlayer"></div>
  </div>

  <div>
    <h1>题目：{{htmlcontent}}</h1>
  </div>
  <div>
    <h1>提交作业截图</h1>
    <el-upload
        class="avatar-uploader"
        action="http://localhost:8080/studyadmin/student/uploadImage"
        multiple
        name="image"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
    >
      <img   v-if="learnImg"  :src="learnImg" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>

  </div>
</template>
<!--<script src="http://code.jquery.com/jquery-latest.js"></script>-->
<script>

import 'vue3-video-play/dist/style.css'
import {videoPlay} from 'vue3-video-play'
import $ from 'jquery'
import {watch} from "vue";

import {useLoginStateStore} from "../../store/storeLoginState.js";
import {ElMessage, ElNotification} from "element-plus";


export default {
  // setup() {
  //   const loginStateStore = useLoginStateStore()
  //   return {
  //     loginStateStore: loginStateStore
  //   }
  // },
  components: {
    videoPlay
  },
  name: "ChapterContent",
  data() {
    return {
      content:'',//内容
      htmlcontent:'',//题目
      learnImg:'',
      chapterDate:'',

      study:0,
      videoId: '', // 记录当前正在播放的videoId
      chaId: '',
      chapter: [],
      player: null,          //播放器
      videoUrl: '',        //视频地址
      videoTitle: '',       //视频标题

      videoSrc: "public/屏幕广播%202022-10-28%2015-39-13.mp4",
      videoName: '', // 记录当前正在播放的小节名称
      allTime: 0, // 总共观看时长，对应字段learning_time
      timer: {},// 计时器对象
      studentVideo: {
        stuNum: '',
        videoId: '',
        learningTime: '',//已学习时长（s）
        duration: '',//视频总时长（s）
        chaId: '',
      }
    }
  },
  watch: {
    '$route': "initCourseInfo",
    study(v1,v2){
      //v1:当前数入的值
      //v2:上一次输入的值
      console.log("0-0-0-0-0--",v1,v2)
    }
  },
  mounted() {
    // this.initCourseInfo();
    // this.getPlayer();
  },

  methods: {
    beforeAvatarUpload(){

    },
    handleAvatarSuccess(res){
      this.learnImg = res.data

      // _this.chaId
      console.log("图片的章节id",this.$route.query.chaId)

      let  stuNum=window.sessionStorage.getItem("userNum")
      // let  stuNum = this.loginStateStore.loginUserName

      let _this = this
      let url = "/studyadmin/student-learnimg/insertStuImgUrl"
      _this.$axios.get(url,{params:{learnImg:_this.learnImg,stuNum:stuNum,chaId:this.$route.query.chaId}}).then(function(data){
        console.log(data)
        if (data.data.code === 0){
          ElMessage.success(data.data.msg)
        }else {
          ElMessage.error(data.data.msg)
        }
      }).catch(function(){

      })
    },



    codeTest() {
      // window.location.href="src/online_editor-master/index2.html";
      window.open('src/online_editor-master/index2.html');
    },
    initCourseInfo() {
      let _this = this;
      this.learnImg='';
      this.chapterDate='';
      this.content='';
      _this.chaId = this.$route.query.chaId
      console.log("0-0-0-00", _this.chaId)
      let url = "/studyadmin/chapter/chapterContentAll";
      _this.$axios.get(url, {params: {chaId: _this.chaId}}).then(function (serverData) {
        console.log("章节内容数据：", serverData.data.data)
        _this.chapterDate=serverData.data.data
        // _this.content=serverData.data.data.content
        if(serverData.data.data.content==null){
          _this.content="";
        }else {
          _this.content=serverData.data.data.content
        }
        if (serverData.data.data.htmlcontent==null){
          _this.htmlcontent="";
        }else {
          _this.htmlcontent=serverData.data.data.htmlcontent
        }


        if (serverData.data.code == 0) {
          //视频
          let url = "/studyadmin/video/chaptervideoContent";
          _this.$axios.get(url, {params: {chaId: _this.chaId}}).then(function (serverData) {
            // console.log("章节内容数据：", serverData.data.data)
            _this.videoUrl = serverData.data.data.videoSourceUrl;
            //视频id
            _this.studentVideo.videoId = serverData.data.data.id
            // console.log("视频地址", _this.videoUrl)
            if (_this.player === null) {
              _this.getPlayer(serverData.data.data.videoSourceUrl);
            } else {
              _this.player.dispose(); //销毁

              $('#J_prismPlayer').empty();
              _this.getPlayer(serverData.data.data.videoSourceUrl);
            }


          }).catch(function (error) {
            console.log("异步请求发生了错误:", error);
          })




        }
      }).catch(function (error) {
        console.log("异步请求发生了错误:", error);
      })

    },

    getPlayer(url) {
      let  stuNum=window.sessionStorage.getItem("userNum")

      let _this = this;
      _this.studentVideo.learningTime='';
      _this.study=0;
      //
      let suspendTime = 0;

      // eslint-disable-next-line no-undef
      this.player = new Aliplayer({
        id: "J_prismPlayer",
        source: url,
        width: "100%",
        height: "400px",
        /* To set an album art, you must set 'autoplay' and 'preload' to 'false' */

        autoplay: false,
        preload: false,
        isLive: false

      }, function (player) {
        let url = "/studyadmin/student-video/progress";
        _this.$axios.get(url, {params:{chaId:_this.chaId,stuNum:stuNum}}).then(function (serverData) {
          // console.log("服务端返回的数据为-----------:", serverData.data.data.lastTime);
          if (serverData.data.code === 0) {
            player.seek(serverData.data.data.lastTime)
          }else {
            player.seek(0)
          }
        })

        console.log("The player is created");
        //定义变量保存时间
        let before = 0;
        //定义变量保存计时器时间
        let time = 0;
        //保存点击按钮暂停的时间

        let timer = undefined
        //视频总时长（s）
        player.on('ready', () => {
          _this.studentVideo.duration = player.getDuration();
          // player.getDuration()


        });
        player.on('play', function () {
          //获取相对的时间
          before = new Date().getTime();
          timer = setInterval(() => {
            //实时时间
            let now = new Date().getTime();
            //计时器时间 = 实时时间 - 相对时间 + 点击暂停按钮时保存的时间
            time = now - before + suspendTime;

            // this.duration = time
            //把处理过的时间显示到content标签中
            // console.log("处理过的时间", time)
          }, 1000);
        })
        player.on('pause', function () {

          //停止计时器
          clearInterval(timer);
          //储存点击暂停的时间
          suspendTime = time / 1000;
          _this.studentVideo.chaId = _this.chaId//章节id
          // console.log("_this.studentVideo.chaId=", _this.studentVideo.chaId)

          _this.studentVideo.stuNum = window.sessionStorage.getItem("userNum")//学生id
          // console.log("_this.loginStateStore.loginUserName=", _this.loginStateStore.loginUserName)
          _this.studentVideo.learningTime = _this.player.getCurrentTime()
          // console.log("当前进度条",)
          console.log("_this.studentVideo", _this.studentVideo)

          let url = "/studyadmin/video/chapterStudentVideo";
          _this.$axios.post(url, _this.studentVideo).then(function (serverData) {
            // console.log("服务端返回的数据为:", serverData.data);
            if (serverData.data.code === 0) {
              ElNotification({
                title: 'Success',
                message: serverData.data.msg,
                type: 'success',
              });
            } else if(serverData.data.count === 3){
              _this.study=serverData.data.count
            }else
            {
              ElNotification({
                title: 'Warning',
                message: serverData.data.msg,
                type: 'warning',
              });
            }
          })


        })

        // player.on("ended", this.endedHandle);
      });
      // this.player.dispose()
    },

  }

}
</script>


<style scoped>

.avatar-uploader .avatar {
  width: 608px;
  height: 408px;
}


.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
